package com.base.core.task.autoconfigure;


import com.base.core.task.parser.ElasticJobConfParser;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * 自动装配
 * 自动装配的前提是@Configuration
 */
@Slf4j
@Configuration
//依赖于这两个属性作为初始化条件判断
@ConditionalOnProperty(prefix = "elastic.job.zk",name={"namespace","serverLists"},matchIfMissing = false)
//引入JobZookeeperProperties 配置类
@EnableConfigurationProperties(value = {JobZookeeperProperties.class})
public class JobParserAutoConfiguration {

    @Bean(initMethod = "init")
    public ZookeeperRegistryCenter  zookeeperRegistryCenter(JobZookeeperProperties jobZookeeperProperties){
        ZookeeperConfiguration zkConfig=new ZookeeperConfiguration(jobZookeeperProperties.getServerLists(),
                jobZookeeperProperties.getNamespace());
        zkConfig.setBaseSleepTimeMilliseconds(jobZookeeperProperties.getBaseSleepTimeMilliseconds());
        zkConfig.setMaxSleepTimeMilliseconds(jobZookeeperProperties.getMaxSleepTimeMilliseconds());
        zkConfig.setConnectionTimeoutMilliseconds(jobZookeeperProperties.getConnectionTimeoutMilliseconds());
        zkConfig.setSessionTimeoutMilliseconds(jobZookeeperProperties.getSessionTimeoutMilliseconds());
        zkConfig.setMaxRetries(jobZookeeperProperties.getMaxRetries());
        zkConfig.setDigest(jobZookeeperProperties.getDigest());

        log.info("初始化job注册中心配置成功,zkaddress:{},namespace:{}",jobZookeeperProperties.getServerLists(),
                jobZookeeperProperties.getNamespace());

        return new ZookeeperRegistryCenter(zkConfig);
    }


    @Bean
    public ElasticJobConfParser elasticJobConfParser(JobZookeeperProperties jobZookeeperProperties,
                                                     ZookeeperRegistryCenter zookeeperRegistryCenter){
        return new ElasticJobConfParser(jobZookeeperProperties,zookeeperRegistryCenter);
    }



}
